import React, { createContext, useContext, useState, useCallback } from 'react';

interface Toast {
  id: string;
  title?: string;
  description?: string;
  variant?: 'default' | 'destructive';
}

interface ToastContextType {
  toasts: Toast[];
  toast: (props: Omit<Toast, 'id'>) => void;
  dismiss: (id: string) => void;
}

const ToastContext = createContext<ToastContextType | undefined>(undefined);

// ToastProvider 组件
interface ToastProviderProps {
  children: React.ReactNode;
}

const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => {
  const [toasts, setToasts] = useState<Toast[]>([]);

  // 创建新的toast
  const toast = useCallback(({ title, description, variant = 'default' }: Omit<Toast, 'id'>) => {
    const id = Math.random().toString(36).substr(2, 9);
    const newToast = { id, title, description, variant };

    setToasts((prev) => [...prev, newToast]);

    // 自动消失
    setTimeout(() => {
      dismiss(id);
    }, 3000);
  }, []);

  // 关闭toast
  const dismiss = useCallback((id: string) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  }, []);

  return (
    <ToastContext.Provider value={{ toasts, toast, dismiss }}>
      {children}
    </ToastContext.Provider>
  );
};

// Toast组件
const Toaster: React.FC = () => {
  const context = useContext(ToastContext);
  
  if (!context) {
    throw new Error('Toaster must be used within a ToastProvider');
  }
  
  const { toasts, dismiss } = context;

  return (
    <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 w-80">
      {toasts.map((toast) => (
        <div
          key={toast.id}
          className={`
            flex items-start gap-3 rounded-md p-4 shadow-lg transition-all duration-300 ease-out
            ${toast.variant === 'destructive' 
              ? 'bg-red-50 text-red-900 dark:bg-red-900/30 dark:text-red-100' 
              : 'bg-white dark:bg-slate-800 text-slate-900 dark:text-white'}
            animate-in fade-in slide-in-from-top-5 duration-300
          `}
        >
          <div className="flex-1">
            {toast.title && (
              <h4 className="font-medium">{toast.title}</h4>
            )}
            {toast.description && (
              <p className="text-sm mt-1 opacity-90">{toast.description}</p>
            )}
          </div>
          <button
            type="button"
            onClick={() => dismiss(toast.id)}
            className="text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 4L4 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              <path d="M4 4L12 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      ))}
    </div>
  );
};

// useToast hook
const useToast = () => {
  const context = useContext(ToastContext);
  
  if (!context) {
    throw new Error('useToast must be used within a ToastProvider');
  }
  
  return context.toast;
};

// 确保Toaster组件能正常工作的辅助包装组件
const EnhancedToaster: React.FC = () => {
  return (
    <ToastProvider>
      <Toaster />
    </ToastProvider>
  );
};

export { Toaster, useToast } from './use-toast';

// 重导出为默认，简化使用
export default EnhancedToaster;